﻿using System;
using System.IO;

namespace GFramework.Netwrok
{
    public sealed class ReceiveState : IDisposable
    {
        private const int DefaultBufferLength = 1024 * 64;
        private MemoryStream _stream;
        private IMessageHeader _messageHeader;
        private bool m_Disposed;

        public ReceiveState()
        {
            _stream = new MemoryStream(DefaultBufferLength);
            _messageHeader = null;
            m_Disposed = false;
        }

        public MemoryStream Stream
        {
            get
            {
                return _stream;
            }
        }

        public IMessageHeader MessageHeader
        {
            get
            {
                return _messageHeader;
            }
        }

        public void PrepareForPacketHeader(int packetHeaderLength)
        {
            Reset(packetHeaderLength, null);
        }

        public void PrepareForPacket(IMessageHeader messageHeader)
        {
            if (messageHeader == null)
            {
                throw new Exception("Packet header is invalid.");
            }

            Reset(messageHeader.PacketLength, messageHeader);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (m_Disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_stream != null)
                {
                    _stream.Dispose();
                    _stream = null;
                }
            }

            m_Disposed = true;
        }

        private void Reset(int targetLength, IMessageHeader messageHeader)
        {
            if (targetLength < 0)
            {
                throw new Exception("Target length is invalid.");
            }

            _stream.Position = 0L;
            _stream.SetLength(targetLength);
            _messageHeader = messageHeader;
        }
    }
}
